
import React, { useEffect, useRef, useState } from 'react'
import { Card, Col, Row, List, Avatar, Drawer } from 'antd';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import axios from 'axios';
import { NavLink } from 'dva/router';
import * as ECharts from 'echarts'
// 数据处理
import _ from 'lodash'

const { Meta } = Card;

export default function Home() {
    // 访问数量数据
    useEffect(() => {
        // _sort = view & _order=desc根据_sort排序，_order为排序方式（desc降序）
        axios(`/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6`).then(res => {
            // console.log(res.data);
            setviewList(res.data)
        })

    }, [])
    // 点赞数量数据
    useEffect(() => {
        // _sort =star & _order=desc根据_sort排序，_order为排序方式（desc降序）
        axios(`/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6`).then(res => {
            // console.log(res.data);
            setstarList(res.data)
        })

    }, [])
    // 取出已发布的所有新闻数据
    useEffect(() => {
        axios(`/news?publishState=2&_expand=category`).then(res => {
            // 将数据以item.category.title进行分组
            // console.log(_.groupBy(res.data, item => item.category.label));
            renderBarView(_.groupBy(res.data, item => item.category.label))

            setallList(res.data)
        })
        return () => {
            // 销毁绑定
            window.onresize = null
        }

    }, [])

    // 数据请求完再显示柱状图
    // 所有数据都有
    const renderBarView = (obj) => {
        // 基于准备好的dom，初始化echarts实例
        var myChart = ECharts.init(barRef.current);

        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '新闻分类图示'
            },
            tooltip: {},
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: Object.keys(obj),
                axisLabel: {
                    rotate: '45',
                    interval: 0
                }
            },
            yAxis: {
                minInterval: 1
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: Object.values(obj).map(item => item.length)
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        // 随着窗口宽度变化，图标自适应
        window.onresize = () => {
            myChart.resize()
        }
    }

    // 数据请求完再显示饼状图
    // 只有关于作者自己的数据
    const renderPieView = (obj) => {
        // 数据处理
        var currentList = allList.filter(item => item.author === username)
        // console.log(currentList);
        var grouoObj = _.groupBy(currentList, item => item.category.label) 
        var list=[]
        for (var i in grouoObj){
            list.push({
                name:i,
                value: grouoObj[i].length
            })
        }

        var myChart
        // 防止多次初始化init
        if (!pieChart) {
            myChart = ECharts.init(pieRef.current);
            setpieChart(myChart)
        } else {
            myChart = pieChart
        }
        var option;
        option = {
            title: {
                text: '当前用户新闻分类图示',
                // subtext: 'Fake Data',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '发布数量',
                    type: 'pie',
                    radius: '50%',
                    data: list,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        option && myChart.setOption(option);
    }
    const [viewList, setviewList] = useState([])
    const [starList, setstarList] = useState([])
    // 所有新闻数据
    const [allList, setallList] = useState([])
    // 抽屉是否显示
    const [visible, setvisible] = useState(false)
    // 存放图标
    const [pieChart, setpieChart] = useState(null)
    const barRef = useRef()
    const pieRef = useRef()

    const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem('token'))
    return (
        <div className="site-card-wrapper">
            <Row gutter={16}>
                <Col span={8}>
                    <Card title="用户最常浏览" bordered={true}>
                        <List
                            size="small"
                            // bordered
                            dataSource={viewList}
                            renderItem={(item) => <List.Item>
                                <NavLink to={`/news-manage/preview/${item.id}`}>{item.label}</NavLink>
                                {/* <a href={`#/news-manage/preview/${item.id}`}></a> */}
                            </List.Item>}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card title="用户点赞最多" bordered={true}>
                        <List
                            size="small"
                            // bordered
                            dataSource={starList}
                            renderItem={(item) => <List.Item>
                                <NavLink to={`/news-manage/preview/${item.id}`}>{item.label}</NavLink>
                            </List.Item>}
                        />
                    </Card>
                </Col>
                {/* 图片 */}
                <Col span={8}>
                    <Card
                        cover={
                            <img
                                alt="example"
                                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                            />
                        }
                        actions={[
                            <SettingOutlined key="setting" onClick={() => {
                                // dom渲染是异步渲染,图表和组件还未创建完就被调用,所有放在异步中
                                setTimeout(() => {
                                    setvisible(true)
                                    // init图标初始化
                                    renderPieView()
                                }, 0)
                            }} />,
                            <EditOutlined key="edit" />,
                            <EllipsisOutlined key="ellipsis" />,
                        ]}
                    >
                        <Meta
                            avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                            title={username}
                            description={
                                <div>
                                    <b>{region ? region : '全球'}</b>
                                    <span style={{ paddingLeft: '30px' }}>{roleName}</span>
                                </div>
                            }
                        />
                    </Card>
                </Col>
            </Row>
            <Drawer
                title="个人新闻分别"
                placement="right"
                onClose={() => {
                    setvisible(false)
                }}
                visible={visible}
                closable={true}
                width='500px'
            >
                <div ref={pieRef} style={{
                    height: '400px',
                    width: '100%',
                    marginTop: '30px'
                }}></div>
            </Drawer>
            <div ref={barRef} style={{
                height: '400px',
                width: '100%',
                marginTop: '30px'
            }}></div>


        </div>
    )
}
